﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlacBox;
using LibEBML.Common;
using NAudio.Wave;
namespace MKVFlacTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string Filename = @"F:\videos\[CASO&SumiSora][Koegoto][OVA02][BDRip][NCOP][x264_flac](8E2EF049).mkv";
            byte[] buf = new byte[65536];
            using (var reader = System.IO.File.OpenRead(Filename))
            {
                using (var buffer = new System.IO.BufferedStream(reader))
                {
                    EBMLDocument document = new EBMLDocument(buffer);
                    Matroska mts = new Matroska(document);
                    Segment seg = mts.Segment;
                    var at = seg.Tracks.Where(m => m.Audio != null).FirstOrDefault();
                    if (at == null)
                    {
                        return;
                    }
                    System.IO.MemoryStream ms = new MemoryStream();
                    ms.Write(at.CodecPrivate, 0, at.CodecPrivate.Length);
                    ms.Position = 0;
                    FlacHeaderReader header = new FlacHeaderReader(ms, true);
                    while (header.Read())
                    {

                    }

                    var cs = seg.Clusters;
                    System.IO.MemoryStream ms2 = new MemoryStream();
                    //foreach (var item in cs)
                    var item = cs[0];
                    {
                        var bs = item.Blocks;
                        //foreach (var item1 in bs)
                        var item1 = bs.Where(m => m.TrackNumber == at.TrackNumber).FirstOrDefault();
                        {
                            if (item1 == null)
                            {
                                return;
                            }
                            var ds = item1.GetBlockData(null);
                            // foreach (var fd in ds)
                            var fd = ds[3];
                            {
                                ms2.Write(fd, 0, fd.Length);
                            }
                            fd = ds[4];
                            {
                                ms2.Write(fd, 0, fd.Length);
                            }
                        }
                    }
                    ms2.Position = 0;
                    WaveOverFlacStream flacStream = new WaveOverFlacStream(header.Streaminfo, ms2);
                    var w = new WaveFormat(48000, 24, 2);
                    WaveOut output = new WaveOut();
                    output.Init(new RawSourceWaveStream(flacStream, w));
                    output.Play();
                    Console.WriteLine("Test");
                }
            }

            Console.ReadLine();
        }
    }
}
